package iscript.coreFramework.displays 
{
	import flash.events.MouseEvent;
	import flash.display.DisplayObject;
	import flash.geom.Rectangle;
	import flash.utils.Dictionary;
	import iscript.coreFramework.math.Point2D;
	import iscript.coreFramework.util.DictionaryUtil;
	public class DragObject 
	{
		
		public function DragObject() 
		{
			_objects = new Dictionary();
		}
		
		
		private var _objects:Dictionary;		
		static private var _dragTarget:DisplayObject;	
		static private var _dragInitializePosition:Point2D = new Point2D(0, 0);
		static private var _instance:DragObject;
		
		static public  function getInstance():DragObject {
			  if (_instance == null) _instance = new DragObject();
			  return  _instance;
			}		
		
		
		public  function add(target:DisplayObject, rect:Rectangle = null ):void {
			    target.addEventListener(MouseEvent.MOUSE_DOWN, _targetMouseDownLogic); 
			    _objects[target] = rect;
				
			
			}
			
		public function remove(target:DisplayObject):void {
			 if (!DictionaryUtil.hasKey(_objects, target)) return;
			  DisplayObject(_objects[target]).removeEventListener(MouseEvent.MOUSE_DOWN, _targetMouseDownLogic); 
			  delete  _objects[target];
			}
		
		
		private function _targetMouseDownLogic(e:MouseEvent):void 
		{
		    //_dragTarget = DisplayObject(e.target);
			 _dragTarget = DisplayObject(e.currentTarget);	 
			 if(_objects[_dragTarget]!=null){
			   if(!Rectangle(_objects[_dragTarget]).contains( _dragTarget.mouseX, _dragTarget.mouseY))
			    return;
			 }
			 
			 _dragTarget.stage.addEventListener(MouseEvent.MOUSE_MOVE, _dragTargetLogic);
			 _dragTarget.stage.addEventListener(MouseEvent.MOUSE_UP, _removedragTargetLogic);
			 
			 _dragInitializePosition = new Point2D(
												   _dragTarget.stage.mouseX - Element.localToGlobal(_dragTarget).x,
												   _dragTarget.stage.mouseY - Element.localToGlobal(_dragTarget).y
												  );
										 
		}	
			
		 
		private function _removedragTargetLogic(e:MouseEvent):void
		{
			_dragTarget.stage.removeEventListener(MouseEvent.MOUSE_MOVE, _dragTargetLogic);
			_dragTarget.stage.removeEventListener(MouseEvent.MOUSE_UP, _removedragTargetLogic);
			 
		}
		
		private function _dragTargetLogic(e:MouseEvent):void 
		{
			 _dragTarget.x =  _dragTarget.stage.mouseX - _dragInitializePosition.x;
			 _dragTarget.y =  _dragTarget.stage.mouseY - _dragInitializePosition.y;
			 e.updateAfterEvent();
		}
			
	 }

}